# coding:utf-8
from django import apps
from django.conf import settings

from zhongbao_admin.models import UserLog, AppLabel, ModelObj, OperateType, Operate

import arrow


# 用户操作类型判断
# 记录用户信息

def model_verify(model, field_dict_list):
    '''
    检验model内相关值是否存在
    :param model:
    :param field_dict_list:
    :return:
    '''
    filter_dict = dict()
    search_dict = field_dict_list[0]
    filter_dict[search_dict['field']] = search_dict['val']
    model_objs = model.objects.filter(**filter_dict)
    if model_objs.count() == 0:
        ret_org = model()
        for f_dict in field_dict_list:
            setattr(ret_org, f_dict['field'], f_dict['val'])
        ret_org.save()
    else:
        ret_org = model_objs[0]
    return ret_org


def record(user, app_label, objtype, obj, operate_type, operate, comment, time, obj_verbose_name=None, comment2=''):
    '''
    :param user:
    :param app_labbel: 所在
    :param objtype: 对象类型
    :param obj: 具体对象
    :param operate_type: 操作类型
    :param operate: 操作
    :param comment: 备注
    :param time: 时间
    :param obj_verbose_name:
    :param comment2:
    :return:
    '''
    objtype = objtype.lower()
    app_label_filed_list = [{'field': 'name', 'val': app_label}, ]
    app_label_model = model_verify(AppLabel, app_label_filed_list)
    if not obj_verbose_name:
        try:
            model = apps.apps.get_model(app_label, objtype)
        except Exception:
            model = None
        if model:
            obj_verbose_name = model._meta.verbose_name
        else:
            obj_verbose_name = ''
    obj_type_filed_list = [{'field': 'name', 'val': objtype}, {'field': 'app_label', 'val': app_label_model.id},
                           {'field': 'verbose_name', 'val': obj_verbose_name}]
    obj_type_model = model_verify(ModelObj, obj_type_filed_list, )
    operate_type_filed_list = [{'field': 'name', 'val': operate_type}, ]
    operate_type_model = model_verify(OperateType, operate_type_filed_list, )

    operate_filed_list = [{'field': 'name', 'val': operate}, {'field': 'model_label', 'val': obj_type_model.id},
                          {'field': 'operate_type', 'val': operate_type_model.id}, ]
    operate_model = model_verify(Operate, operate_filed_list, )

    u_record = UserLog(user_id=user.id, app_label=app_label, author=user.nickname, obj_type=objtype, obj=obj,
                       operate_type=operate_type, operate=operate, comment=comment, time=time, comment2=comment2)
    u_record.save()


def error_mes_get(logger, error_mes):
    time_tag = arrow.now(settings.TIME_ZONE).timestamp
    log_mes = str(time_tag) + ':----' + error_mes + '\n'
    logger.error(log_mes)
    mes = '错误代码：{}'.format(time_tag)
    return mes
